define(window.backboneCommon.getViewDefine("customer.detail"), function ($,require,Collection,tpl) {
    var backboneView= Backbone.View.extend({
        events: {
            "click #btn_addImg_industry": "addImgIndustry",
            "click #btn_addImg_ad": "addImgAd",
            "click .remove-file": "deleteImgFile",
            "click #btn_submitAudit": "submitAudit",
            "click #btn_submitSave": "submitSave"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.baseData=this.model.get("modelBaseData");
            this.listenTo(this.modelAttach.baseData, 'bind:Industry', this.bindIndustry);
            this.listenTo(this.model, 'bind:Info', this.bindInfo);
            this.listenTo(this.model, 'save:Info', this.saveInfoCallback);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(id){
            this.elementModel={};
            this.extObject={};
            this.pageData={customerId:id};
            this.elementModel.form=$("#form_detail");
            this._initPagePower();
        },
        _initPagePower:function(){
            var self=this;
            $.ExtAssist.rolePower.operatePage("create|edit",[],function(json){
                self.pageData.powerInfo=json;
                self._initBodyMain();
            });
        },
        _initBodyMain:function(){
            this.collection.getInfo(this.pageData.customerId);
            $.ExtAssist.urlParam.setUrl();
        },
        bindInfo:function () {
            var self=this;
            var result=this.model.get("dataInfo");
            self.pageData.isAdd=result.isAdd;
            $(".page-operate-title").text($.ExtCommon.getStringConnect("{0}广告主",self.pageData.isAdd?"新建":"编辑"));
            self.extObject.formValue=self.elementModel.form.ExtFormValue({initValue:result.res.data,
                initCallback:function(dataJson){
                    self.pageData.customerInfo=dataJson;
                    self._initImgPanel();
                    self.elementModel.form.ExtParsley();
                    self.collection.initAfterDetail();
                }
            });
            if (!result.res.success) {$.ExtNotify.error("该广告主数据获取失败：" +result.res.msg)}
        },
        bindIndustry:function () {
            var self=this;
            var res=self.modelAttach.baseData.get("dataIndustry");
            $("#txt_industryType").ExtSelect2Tree({width:"w-500",placeholder:"-请选择-",data:res.data,
                changeCallback:function(element){self.elementModel.form.ExtParsley().validate(element);}
            });
        },
        _initImgPanel:function () {
            var self = this;
            var img = {};
            img.industry = $.map(self.pageData.customerInfo.industryImgData, function (iu) {
                return {type: "industry", msgTop: "行业资质", url: iu.url, imgId: iu.id}
            });
            img.ad = $.map(self.pageData.customerInfo.adImgData, function (au) {
                return {type: "ad", msgTop: "广告资质", url: au.url, imgId: au.id}
            });
            for (var i in img) {
                if (img.hasOwnProperty(i)) {
                    $("#panel_img_" + i).html($("#template_img").render(img[i]));
                    self._disabledAddImg(i);
                }
            }
            if (!$.ExtCommon.isCheckEmpty(self.pageData.customerInfo.licenseImgData.id)) {
                $("#file_license").data("imgId", self.pageData.customerInfo.licenseImgData.id)
            }
            if (!$.ExtCommon.isCheckEmpty(self.pageData.customerInfo.icpImgData.id)) {
                $("#file_icp").data("imgId", self.pageData.customerInfo.icpImgData.id)
            }
            self._initUpLoadImg();
        },
        _initUpLoadImg:function() {
            var self=this;
            var url= self.modelAttach.baseData.get("defUploadImgUrl");
            $.each(self.elementModel.form.find(".init-file"),function (i,item) {
                var element = $(item);
                var thisData = element.data();
                element.removeClass("init-file");
                element.ExtUploadFile({
                    "tipmsg_top": thisData["msgtipTop"],
                    "tipmsg_bottom": thisData["msgtipBottom"],
                    maxSize: thisData["imgSize"],
                    imgSrcUrl: thisData["url"],
                    spanWidth:"490",
                    beforeRemoveCallback: function (obj) {
                        obj.siblings(".box-file").removeData("url").removeData("imgId");
                    },
                    ajaxInfoCallback: {
                        url: url,
                        "success": function (element, resData) {
                            element.data({url:resData.imageUrl,imgId:resData.imageId});
                            self.elementModel.form.ExtParsley().validate(element);
                        }
                    }
                });
            });
        },
        _disabledAddImg:function (type) {
            $("#btn_addImg_"+type).prop("disabled", $("#panel_img_"+type).children().length>=15);
        },
        _addUpLoadImg:function (type) {
            var el=$("#panel_img_"+type);
            if(el.children().length<15) {
                el.append($("#template_img").render({type: type, msgTop: type === "industry" ? "行业资质" : "广告资质"}));
                this._initUpLoadImg();
            }
            this._disabledAddImg(type)
        },
        addImgIndustry:function () {
            this._addUpLoadImg("industry");
        },
        addImgAd:function () {
            this._addUpLoadImg("ad");
        },
        deleteImgFile:function (e) {
            var el = $(e.currentTarget);
            var type=el.data("type");
            el.parent().remove();
            this._disabledAddImg(type);
        },

        _checkForm:function(){
            $.ExtNotify.destroy();
            var isExtCheck=true;
            $.each(this.elementModel.form.find(":file[required]"),function (i,item) {
                var elFile=$(item);
                $.ExtCommon.isCheckEmpty(elFile.data("url"))? elFile.attr("required",""): elFile.removeAttr("required");
            });
            return this.elementModel.form.ExtParsley("validate") && isExtCheck;
        },
        submitSave:function () {
            this.saveData(false);
        },
        submitAudit:function () {
            this.saveData(true);
        },
        _getUploadImg:function (type) {
            var arr=[];
            $.each($("#panel_img_"+type).find(":file"),function (i,item) {
                var elData=$(item).data();
                if(!$.ExtCommon.isCheckEmpty(elData.url) && !$.ExtCommon.isCheckEmpty(elData.imgId)){
                    arr.push({id:elData.imgId,url:elData.url});
                }
            });
            return arr;
        },
        saveData:function (isAudit) {
            if(this._checkForm()) {
                var infoOriginal = this.elementModel.form.ExtFormValue("getOriginalData");
                var ajaxData = this.elementModel.form.ExtFormValue("getValues");
                ajaxData.licenseImgData={};
                ajaxData.icpImgData={};
                if(!$.ExtCommon.isCheckEmpty(ajaxData.licenseImg)){ajaxData.licenseImgData={id:$("#file_license").data("imgId"),url:ajaxData.licenseImg}}
                if(!$.ExtCommon.isCheckEmpty(ajaxData.icpImg)){ajaxData.icpImgData={id:$("#file_icp").data("imgId"),url:ajaxData.icpImg}}
                ajaxData.industryImgData=this._getUploadImg("industry");
                ajaxData.adImgData=this._getUploadImg("ad");
                ajaxData.audit = isAudit;
                if (infoOriginal.id) {ajaxData.id = infoOriginal.id}
                this.collection.saveInfo(ajaxData);
            }
        },
        saveInfoCallback:function () {
            var result=this.model.get("dataSave");
            if (result.res.success) {
                $.ExtNotify.success("保存成功!");
                if(result.isAdd){$.ExtAssist.pageListParam.setData("targetPackList",null)}
                $.ExtAssist.goUrlHref("#customer");
            }else{
                $.ExtNotify.error(result.res.msg);
            }
        }
    });
    var viewModel=function(){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el: "#container_body",collection:this.collection,model:this.model});
    };
    viewModel.prototype={
        initView:function (param) {
            var id=param?param[0]:null;
            this.view.initMain(id);
        }
    };
    return viewModel;
});